﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Web.Mvc;
using UICommon.ConvertVedio;
using UICommon.Result;
using UICommon.ExtendHtmlHelper;
using Model;
using BLL;
using System.Collections;

namespace UICommon.ExtendController
{
    public class FileProcessController : Controller
    {
        private string UploadCover()
        {
            return System.Configuration.ConfigurationManager.AppSettings["UploadPath"].ToString();
        }

        private string Website()
        {
            return System.Configuration.ConfigurationManager.AppSettings["website"].ToString();
        }

        public Int64 SaveResource(HttpPostedFileBase file)
        {
            //string fileCategoryName = "";

            //switch (fileCategory)
            //{
            //    case 0:
            //        fileCategoryName = "论坛";
            //        break;

            //    case 1:
            //        fileCategoryName = "习题";
            //        break;

            //    case 2:
            //        fileCategoryName = "电子书";
            //        break;

            //    case 3:
            //        fileCategoryName = "作业";
            //        break;

            //    case 4:
            //        fileCategoryName = "电子书图片";
            //        break;

            //    case 5:
            //        fileCategoryName = "通知";
            //        break;

            //    case 6:
            //        fileCategoryName = "站内信";
            //        break;

            //    default:
            //        fileCategoryName = "其他";
            //        break;
            //}

            string fileKey = Guid.NewGuid().ToString();

            string fileName = Path.GetFileName(file.FileName);

            string sqlPath = Path.Combine(new string[] { 
                "Cover",
                //fileCategoryName,
                //user.UserName,
                Path.GetExtension(fileName).TrimStart('.'),
                fileKey
            });

            string dicPath = Path.Combine(UploadCover(),sqlPath);

            Directory.CreateDirectory(dicPath);

            file.SaveAs(Path.Combine(dicPath, fileName));

            TransfromVideo(Path.Combine(dicPath, fileName));

            return SaveResourceToSql(file, sqlPath);
        }

        public Int64 SaveResourceToSql(HttpPostedFileBase baseFile, string path)
        {
            try
            {
                //Domain.ContentModel.File file = new Domain.ContentModel.File();
                //file.MIME = baseFile.ContentType;
                //file.Size = baseFile.ContentLength;
                //file.Name = baseFile.FileName;
                //file.Path = path;
                //file.Property = "";
                //file.User = user;

                ////bool isSave = EntAppFrameWork.EntAppFrameWorkContext.Application.Save<Domain.ContentModel.File, Int64>(file);

                //return file.Key;

                Resource file = new Resource();
                file.MIME = baseFile.ContentType;
                file.Size = baseFile.ContentLength;
                file.Name = baseFile.FileName;
                file.Path = path;
                file.Property = "";
                file.CreateTime = DateTime.Now;
                file.LastUpdateTime = DateTime.Now;

                Resource_BLL bll = new Resource_BLL();
                return bll.Add2(file);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #region 视频转换

        private void TransfromVideo(string pathAndFileName)
        {
            string fileName = Path.GetFileName(pathAndFileName);
            string dic = Path.GetDirectoryName(pathAndFileName);
            string fileNameNoExtension = Path.GetFileNameWithoutExtension(fileName);

            ConvertVedioProcess convertMp4 = new ConvertVedioProcess();
            ConvertVedioProcess convertWebM = new ConvertVedioProcess();

            if (convertMp4.CheckIsSupportVideo(fileName))
            {
                string extension = Path.GetExtension(fileName);

                switch (extension)
                {
                    case ".mp4":
                        System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadConvertToWebM));
                        IList<String> listStr = new List<String>();
                        listStr.Add(pathAndFileName);
                        listStr.Add(string.Format(@"{0}\{1}.webm", dic, fileNameNoExtension));
                        t1.Start(listStr);
                        //convertWebM.ConvertToWebM(this.TransfromTool, pathAndFileName, string.Format(@"{0}\{1}.webm", dic, fileNameNoExtension));
                        break;

                    case ".webm":
                        System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadConvertToMP4));
                        IList<String> listStr1 = new List<String>();
                        listStr1.Add(pathAndFileName);
                        listStr1.Add(string.Format(@"{0}\{1}.mp4", dic, fileNameNoExtension));
                        t2.Start(listStr1);
                        //1.工具  2.上传文件的路径  3.需要转换的路径
                        //convertMp4.Convert(this.TransfromTool, pathAndFileName, string.Format(@"{0}\{1}.mp4", dic, fileNameNoExtension));
                        break;

                    case ".ogg":
                        System.Threading.Thread t5 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadConvertToOgg));
                        IList<String> listStrOgg = new List<String>();
                        listStrOgg.Add(pathAndFileName);
                        listStrOgg.Add(string.Format(@"{0}\{1}.ogg", dic, fileNameNoExtension));
                        t5.Start(listStrOgg);
                        //1.工具  2.上传文件的路径  3.需要转换的路径
                        //convertMp4.Convert(this.TransfromTool, pathAndFileName, string.Format(@"{0}\{1}.mp4", dic, fileNameNoExtension));
                        break;

                    default:

                        System.Threading.Thread t3 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadConvertToWebM));
                        IList<String> listStr3 = new List<String>();
                        listStr3.Add(pathAndFileName);
                        listStr3.Add(string.Format(@"{0}\{1}.webm", dic, fileNameNoExtension));
                        t3.Start(listStr3);

                        System.Threading.Thread t4 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadConvertToMP4));
                        IList<String> listStr4 = new List<String>();
                        listStr4.Add(pathAndFileName);
                        listStr4.Add(string.Format(@"{0}\{1}.mp4", dic, fileNameNoExtension));
                        t4.Start(listStr4);

                        System.Threading.Thread t6 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadConvertToOgg));
                        IList<String> listStr6 = new List<String>();
                        listStr6.Add(pathAndFileName);
                        listStr6.Add(string.Format(@"{0}\{1}.ogg", dic, fileNameNoExtension));
                        t6.Start(listStr6);

                        //convertMp4.Convert(this.TransfromTool, pathAndFileName, string.Format(@"{0}\{1}.mp4", dic, fileNameNoExtension));
                        //convertWebM.ConvertToWebM(this.TransfromTool, pathAndFileName, string.Format(@"{0}\{1}.webm", dic, fileNameNoExtension));
                        break;
                }
            }
        }

        private void ThreadConvertToWebM(object url)
        {
            IList<String> list =(List<String>) url;

            string pathAndFileName = list[0];
            string path = list[1];

            ConvertVedioProcess convertWebM = new ConvertVedioProcess();

            convertWebM.ConvertToWebM(this.TransfromTool, pathAndFileName, path);
        }

        private void ThreadConvertToMP4(object url)
        {
            IList<String> list = (List<String>)url;

            string pathAndFileName = list[0];
            string path = list[1];

            ConvertVedioProcess convertMP4 = new ConvertVedioProcess();

            convertMP4.Convert(this.TransfromTool, pathAndFileName, path);
        }

        private void ThreadConvertToOgg(object url)
        {
            IList<String> list = (List<String>)url;

            string pathAndFileName = list[0];
            string path = list[1];

            ConvertVedioProcess convertOgg = new ConvertVedioProcess();

            convertOgg.ConvertToOgg(this.TransfromTool, pathAndFileName, path);
        }

        /// <summary>
        /// 转换工具路径
        /// </summary>
        private string TransfromTool
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["ffmpeg"].ToString();
            }
        }

        #endregion

        #region 下载文件

        //public FileResult DownLoad(Int64 id = 0)
        //{
        //    //Domain.ContentModel.File file = EntAppFrameWork.EntAppFrameWorkContext.Application.Retrieve<Domain.ContentModel.File, Int64>(id);
        //    Resource file = null;

        //    return File(Path.Combine(file.Path, file.Name), file.MIME, file.Name);
        //}

        public ActionResult DownLoad(Int64 id = 0)
        {
            #region
            //增加视频处理
            //string browserType2 = Request.QueryString["type"];
            //if (!string.IsNullOrEmpty(browserType2))
            //{
            //    switch (browserType2)
            //    {
            //        case "mp4":
            //            this.Response.Redirect("/FileProcess/DownLoad2/"+id+".mp4?type=mp4");
            //            break;

            //        case "webm":
            //            this.Response.Redirect("/FileProcess/DownLoad2/" + id + ".webm?type=webm");
            //            break;
            //    }
            //}
            #endregion
            //Domain.ContentModel.File file = EntAppFrameWork.EntAppFrameWorkContext.Application.Retrieve<Domain.ContentModel.File, Int64>(id);
            Resource_BLL bll = new Resource_BLL();
            Resource file = bll.GetById(id);

            string path = UploadCover();

            string fileName = Path.Combine(new string[] { path, file.Path, file.Name });

            if (System.IO.File.Exists(fileName))
            {
                if (ExtendBaseFile.CheckVideo(Path.GetExtension(fileName).ToLower()))
                {
                    string downExtention = "mp4";
                    string downMime = "mp4";
                    string browserType = Request.QueryString["type"];

                    if (!string.IsNullOrEmpty(browserType))
                    {
                        switch (browserType)
                        {
                            case "mp4":
                                downExtention = "mp4";
                                downMime = "mp4";
                                break;

                            case "webm":
                                downExtention = "webm";
                                downMime = "webm";
                                break;
                        }
                    }
                    fileName = string.Format("{0}.{1}", Path.GetFileNameWithoutExtension(fileName), downExtention);

                    #region

                    //this.HttpContext.Response.AddHeader("Accept-Ranges", "bytes");
                    //FileStream fileStream = System.IO.File.OpenRead(Path.Combine(UploadCover(), file.Path, fileName));
                    //return File(fileStream, string.Format("video/{0}", downMime));
                    FileInfo videoFileInfo = new FileInfo(Path.Combine(UploadCover(), file.Path, fileName));
                    return new ResumableDownloadResult(videoFileInfo, string.Format("video/{0}", downMime));

                    #endregion
                    //return File(Path.Combine(UploadCover(), file.Path, fileName), string.Format("video/{0}", downMime), fileName);
                }

                if (ExtendBaseFile.CheckMP3(Path.GetExtension(fileName)))
                {
                    //this.HttpContext.Response.AddHeader("Accept-Ranges", "bytes");
                    //FileStream fileStream = System.IO.File.OpenRead(Path.Combine(UploadCover(), file.Path, fileName));
                    //return File(fileStream, string.Format("video/{0}", "mp3"));

                    FileInfo mp3FileInfo = new FileInfo(fileName);
                    return new ResumableDownloadResult(mp3FileInfo, "audio/mpeg");
                }

                if (ExtendBaseFile.CheckFlash(Path.GetExtension(fileName)))
                {
                    //this.HttpContext.Response.AddHeader("Accept-Ranges", "bytes");
                    //FileStream fileStream = System.IO.File.OpenRead(Path.Combine(UploadCover(), file.Path, fileName));
                    //return File(fileStream, string.Format("video/{0}", "flash"));
                    FileInfo flashFileInfo = new FileInfo(fileName);
                    return new ResumableDownloadResult(flashFileInfo, "application/x-shockwave-flash");
                }

                //return File(fileName, file.MIME, file.Name);
                FileInfo fileInfo = new FileInfo(fileName);
                return new ResumableDownloadResult(fileInfo, file.MIME);
            }
            else
            {
                string type = Request.QueryString["type"];

                string url = "";

                if (string.IsNullOrEmpty(type))
                {
                    url = Website() + string.Format("/Courseware/DownLoad/{0}", id);
                }
                else
                {
                    url = Website() + string.Format("/Courseware/DownLoad/{0}?type={1}", id, type);
                }

                Response.Redirect(url);
                Response.End();

                return null;
            }
        }

        public static bool IsFileInUse(string fileName)
        {
            bool inUse = true;

            FileStream fs = null; 
            try
            {

                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
                    FileShare.None);

                fs.Close();
                
            } 
            catch(Exception ex){

            }
            return inUse;//true表示正在使用,false没有使用
        }
        public FileResult DownLoad2(String id)
        {
            int position = id.ToLower().IndexOf(".mp4");
            if (position == -1)
                position = id.ToLower().IndexOf(".webm");
            if (position == -1)
                return null;
            id = id.Substring(0, position);

            //Domain.ContentModel.File file = EntAppFrameWork.EntAppFrameWorkContext.Application.Retrieve<Domain.ContentModel.File, Int64>(long.Parse(id));
            Resource file = null;

            string path = UploadCover();

            string fileName = Path.Combine(new string[] { path, file.Path, file.Name });

            if (System.IO.File.Exists(fileName))
            {
                if (ExtendBaseFile.CheckVideo(Path.GetExtension(fileName)))
                {
                    string downExtention = "mp4";
                    string downMime = "mp4";
                    string browserType = Request.QueryString["type"];

                    if (!string.IsNullOrEmpty(browserType))
                    {
                        switch (browserType)
                        {
                            case "mp4":
                                downExtention = "mp4";
                                downMime = "mp4";
                                break;

                            case "webm":
                                downExtention = "webm";
                                downMime = "webm";
                                break;
                        }
                    }
                    fileName = string.Format("{0}.{1}", Path.GetFileNameWithoutExtension(fileName), downExtention);

                    #region 

                    this.HttpContext.Response.AddHeader("Accept-Ranges", "bytes");
                    FileStream fileStream = System.IO.File.OpenRead(Path.Combine(UploadCover(), file.Path, fileName));
                    return File(fileStream, string.Format("video/{0}", downMime));

                    #endregion
                    //return File(Path.Combine(UploadCover(), file.Path, fileName), string.Format("video/{0}", downMime), fileName);
                }

                if (ExtendBaseFile.CheckMP3(Path.GetExtension(fileName)))
                {
                    this.HttpContext.Response.AddHeader("Accept-Ranges", "bytes");
                    FileStream fileStream = System.IO.File.OpenRead(Path.Combine(UploadCover(), file.Path, fileName));
                    return File(fileStream, string.Format("video/{0}", "mp3"));
                }

                if (ExtendBaseFile.CheckFlash(Path.GetExtension(fileName)))
                {
                    this.HttpContext.Response.AddHeader("Accept-Ranges", "bytes");
                    FileStream fileStream = System.IO.File.OpenRead(Path.Combine(UploadCover(), file.Path, fileName));
                    return File(fileStream, string.Format("video/{0}", "flash"));
                }

                return File(fileName, file.MIME, file.Name);
            }
            else
            {
                string type = Request.QueryString["type"];

                string url = "";

                if (string.IsNullOrEmpty(type))
                {
                    url = Website() + string.Format("/Courseware/DownLoad/{0}", id);
                }
                else
                {
                    url = Website() + string.Format("/Courseware/DownLoad/{0}?type={1}", id, type);
                }

                Response.Redirect(url);
                Response.End();

                return null;
            }
        }

        #endregion

        #region 上传图片

        private int maxSize = 1000000;

        public JsonResult UploadImage(int id)
        {
            try
            {
                HttpPostedFileBase imgFile = Request.Files[0];

                if (imgFile == null)
                {
                    throw new Exception("请选择文件！");
                }

                if (!imgFile.CheckImage())
                {
                    throw new Exception("图片格式不正确！");
                }

                if (imgFile.InputStream.Length > maxSize)
                {
                    throw new Exception("图片太大，建议小于4M！");
                }

                Int64 fileKey = this.SaveResource(imgFile);

                Hashtable hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = string.Format("/FileProcess/DownLoad/{0}", fileKey);

                return Json(hash, "text/html", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        //#endregion

        //protected Domain.UserModel.User CurrentUser
        //{
        //    get
        //    {
        //        try
        //        {
        //            return HttpContext.Session["ss_User"] == null
        //                       ? GetCurrentUser()
        //                       : (HttpContext.Session["ss_User"] as Domain.UserModel.User);
        //        }
        //        catch
        //        {
        //            throw;
        //        }
        //    }
        //}

        //private Domain.UserModel.User GetCurrentUser()
        //{
        //    UserUserNameEqualSpecification userNameSpec = new UserUserNameEqualSpecification(HttpContext.User.Identity.Name);

        //    var users = EntAppFrameWork.EntAppFrameWorkContext.Application.FindAll<User, Int64>(userNameSpec);

        //    if (users != null && users.Count > 0)
        //    {
        //        HttpContext.Session["ss_User"] = users[0];
        //        return users[0];
        //    }

        //    return null;
        //}

        //public FileResult DownLoadFile(Int64 id)
        //{
        //    Domain.ContentModel.File file = EntAppFrameWork.EntAppFrameWorkContext.Application.Retrieve<Domain.ContentModel.File, Int64>(id);

        //    string path = UploadCover();

        //    string fileName = Path.Combine(new string[] { path, file.Path, file.Name });

        //    if (System.IO.File.Exists(fileName))
        //    {
        //        return File(fileName, file.MIME, file.Name);
        //    }
        //    else
        //    {
        //        string type = Request.QueryString["type"];

        //        string url = "";

        //        if (string.IsNullOrEmpty(type))
        //        {
        //            url = Website() + string.Format("/Courseware/DownLoad/{0}", id);
        //        }
        //        else
        //        {
        //            url = Website() + string.Format("/Courseware/DownLoad/{0}?type={1}", id, type);
        //        }

        //        Response.Redirect(url);
        //        Response.End();

        //        return null;
        //    }
        //}

        //#region 删除文件

        //public JsonResult DelFile(Int64 id)
        //{
        //    Domain.ContentModel.File file = EntAppFrameWork.EntAppFrameWorkContext.Application.Retrieve<Domain.ContentModel.File, Int64>(id);

        //    string path = UploadCover();

        //    string fileName = Path.Combine(path, file.Path);
            
        //    bool target = EntAppFrameWork.EntAppFrameWorkContext.Application.Remove<Domain.ContentModel.File, Int64>(file);

        //    if (target)
        //    {
        //        Directory.Delete(fileName,true);
        //    }

        //    return Json(target, JsonRequestBehavior.AllowGet);
        //}

        #endregion
    }
}
